﻿using System;
using System.IO;
using System.Security.AccessControl;
using Microsoft.VisualBasic;
using System.Windows.Forms;

namespace Yak
{
    internal class FSUtils
    {
        internal static void CopyDirectory(string Src, string Dst)
        {
            String[] Files;

            if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar)
                Dst += Path.DirectorySeparatorChar;
            if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
            Files = Directory.GetFileSystemEntries(Src);
            foreach (string Element in Files)
            {
                // Sub directories
                if (Directory.Exists(Element))
                    CopyDirectory(Element, Dst + Path.GetFileName(Element));
                // Files in directory
                else
                    File.Copy(Element, Dst + Path.GetFileName(Element), true);
            }
        }

        internal static Int64 DirectorySize(DirectoryInfo d)
        {
            Int64 Size = 0;
            // Add file sizes.
            FileInfo[] fis = d.GetFiles();
            foreach (FileInfo fi in fis)
            {
                Size += fi.Length;
            }
            // Add subdirectory sizes.
            DirectoryInfo[] dis = d.GetDirectories();
            foreach (DirectoryInfo di in dis)
            {
                Size += DirectorySize(di);
            }
            return (Size);
        }

        internal static String GetSizeString(Int64 Size)
        {
            if (Size < 512000)
            {
                return(Size / 1024).ToString()+"Kilobyte";
            }
            else if (Size < 4194304000)
            {
                return(Size / 1048576).ToString()+"Megabyte";
            }
            else
            {
                return(Size / 1073741824).ToString()+"Gigabyte";
            }
        }

        internal static String GetRoot(String Folder)
        {
                return (new DirectoryInfo(Folder).Root.ToString());
        }
        
        internal static bool CanIWrite (String Folder)
        {
            try
            {
                DirectorySecurity ds = Directory.GetAccessControl(Folder);

                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }
    }

    internal static class Env
    {
        internal static String ProjectName
        {
            get
            {
                try
                {
                    throw (new Exception());
                }
                catch (Exception ex)
                {
                    return (ex.Source);
                }
            }
        }
    }
}